<template>
  <div>
    <ContentWrap>
      <div class="flex flex-justify-between">
        <div class="w-350px">
          目录
          <div id="draggable-box">
            <div v-for="(menu, menuIndex) in menuList" :key="menuIndex" class="mt-12px">
              <el-select v-model="menu.dataObj" clearable placeholder="请选择数据对象" disabled>
                <el-option
                  v-for="(item, index) in dataObjectList"
                  :key="index"
                  :label="item.value"
                  :value="item.key"
                />
              </el-select>
              <!-- <el-button
                :icon="Minus"
                size="small"
                circle
                @click="delItem(menuIndex)"
                v-if="menuIndex !== 0"
                class="ml-12px"
              />
              <el-button
                :icon="Plus"
                size="small"
                circle
                @click="addItem(menuIndex)"
                class="ml-12px"
              /> -->
            </div>
          </div>
        </div>
        <el-card shadow="never" class="chart-wrap">
          <div class="text-center font-size-24px">
            {{ preData.name }}
          </div>
          <div class="mt-12px text-center"> {{ titleTime.startTime }}-{{ titleTime.endTime }} </div>
          <div>
            <div v-for="(obj, objIndex) in menuList" :key="objIndex" class="mb-22px">
              <SubTitle :title="objectMap.get(obj.dataObj)" />
              <div class="chart-list" :id="`chart-box${objIndex}`">
                <div
                  v-for="(chart, chartIndex) in obj.temp"
                  :key="chartIndex"
                  :class="`${chart.type}-css`"
                  class="text-right"
                >
                  <el-button
                    :icon="Close"
                    size="small"
                    circle
                    v-if="!route.query.id"
                    @click="CloseChart(objIndex, chartIndex)"
                    class="ml-12px"
                  />
                  <div v-if="chart.type == 'Table'">
                    <el-table :data="tableData" style="width: 100%">
                      <el-table-column prop="name" label="" />
                      <el-table-column prop="database" label="数据库资产" />
                      <el-table-column prop="file" label="文件资产" />
                    </el-table>
                  </div>
                  <div v-if="chart.type == 'Pie'">
                    <Echart :height="300" :options="pieOptionsData" />
                  </div>
                  <div v-if="chart.type == 'Bar'">
                    <Echart :height="300" :options="barOptionsData" />
                  </div>
                  <div v-if="chart.type == 'Line'">
                    <Echart :height="300" :options="lineOptionsData" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <div class="mt-20px text-center" v-if="preData.tempId">
        <el-button type="primary" @click="cancel">上一步</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </div>
    </ContentWrap>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import SubTitle from '@/components/SubTitle/index.vue'
import Sortable from 'sortablejs'
import { Close } from '@element-plus/icons-vue'
import * as reportManageApi from '@/api/report/reportManage/index'
import * as reportTempApi from '@/api/report/reportTemp/index'
import { EChartsOption } from 'echarts'
import { barOptions, lineOptions, pieOptions } from '@/views/report/display/echarts-data'
import dayjs from 'dayjs'
const route = useRoute()
const router = useRouter()
const preData = ref(route.query)
const titleTime = ref({ startTime: '', endTime: '' })
titleTime.value.startTime = dayjs(preData.value?.startTime).format('YYYY-MM-DD')
titleTime.value.endTime = dayjs(preData.value?.endTime).format('YYYY-MM-DD')
const sortableRef = ref(null)
const menuList = ref([
  {
    dataObj: '数据保护标准',
    temp: [
      {
        type: 'Table',
        dataObj: 'StandardStatistics'
      },
      {
        type: 'Pie',
        dataType: 'database',
        dataObj: 'StandardStatistics'
      },
      {
        type: 'Pie',
        dataType: 'file',
        dataObj: 'StandardStatistics'
      }
    ]
  },
  {
    dataObj: '类别',
    temp: [
      {
        type: 'Table',
        dataObj: 'ClassificationStatistics'
      },
      {
        type: 'Bar',
        dataType: 'database',
        dataObj: 'ClassificationStatistics'
      },
      {
        type: 'Bar',
        dataType: 'file',
        dataObj: 'ClassificationStatistics'
      }
    ]
  }
])

const tableData = [
  {
    name: '名称',
    database: '数据库资产数量',
    file: '文件资产数量'
  },
  {
    name: '名称',
    database: '数据库资产数量',
    file: '文件资产数量'
  },
  {
    name: '名称',
    database: '数据库资产数量',
    file: '文件资产数量'
  }
]

const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption
const lineOptionsData = reactive<EChartsOption>(lineOptions) as EChartsOption

const CloseChart = (objIndex, chartIndex) => {
  menuList.value[objIndex].temp.splice(chartIndex, 1)
}

const delItem = (index) => {
  menuList.value.splice(index, 1)
}
const addItem = (index) => {
  menuList.value.splice(index + 1, 0, { dataObj: '数据保护标准' })
}

const dragTable = () => {
  const el: any = document.getElementById('draggable-box')
  Sortable.create(el, {
    animation: 200,
    chosenClass: 'chosenClass', // 被选中项的css 类名
    onEnd: (evt) => {
      let { oldIndex, newIndex } = evt
      menuList.value.splice(newIndex, 0, menuList.value.splice(oldIndex, 1)[0])
      const arr = menuList.value.slice(0)
      menuList.value = []
      nextTick(() => {
        menuList.value = arr
        console.log('menuList.value', menuList.value)
        setTimeout(() => {
          dragChart()
        }, 1000)
      })
    }
  })
}
const dragChart = () => {
  menuList.value.forEach((item, index) => {
    const el: any = document.getElementById(`chart-box${index}`)
    Sortable.create(el, {
      group: 'shared',
      animation: 200,
      filter: '.Table-css',
      chosenClass: 'chosenClass', // 被选中项的css 类名
      onEnd: (evt) => {
        const { newIndex, oldIndex } = evt
        const fromIndex = evt.from.id.replace('chart-box', '')
        const toIndex = evt.to.id.replace('chart-box', '')
        menuList.value[toIndex].temp.splice(
          newIndex,
          0,
          menuList.value[fromIndex].temp.splice(oldIndex, 1)[0]
        )
        const arr = menuList.value.slice()
        menuList.value = []
        nextTick(() => {
          menuList.value = arr
          console.log('menuList.value', menuList.value)
          // 解决数组改变后拖动失效问题
          setTimeout(() => {
            dragChart()
          }, 1000)
        })
      }
    })
  })
}

const confirm = async () => {
  const composing = JSON.stringify(menuList.value)
  console.log('composing', composing)
  // if(preData.value.startTime||preData.value.endTime){

  // }
  const data = await reportManageApi.reportManageCreate({ ...preData.value, composing })
  console.log('data', data)
  if (data) {
    ElMessage.success('操作成功')
    router.back()
  }
}
const cancel = () => {
  router.push({
    path: '/report/reportManage',
    query: {
      isFromEdit: 'true',
      ...preData.value
    }
  })
}

const convertData = (data) => {
  const menuList: any = []

  data.forEach((item) => {
    const temp: any = []
    item.view.forEach((viewItem) => {
      if (viewItem.chartsType === 'Table') {
        temp.push({
          type: 'Table',
          dataObj: item.dataObject
        })
      } else {
        temp.push({
          type: viewItem.chartsType,
          dataType: 'database', // 此处假设 dataType 默认为 'database'，你可以根据实际情况修改
          dataObj: item.dataObject
        })
        temp.push({
          type: viewItem.chartsType,
          dataType: 'file',
          dataObj: item.dataObject
        })
      }
    })

    menuList.push({
      dataObj: item.dataObject,
      temp: temp
    })
  })

  return menuList
}

// 数据对象列表
const dataObjectList = ref()
const objectMap = new Map([
  ['StandardStatistics', '数据保护标准'],
  ['ClassificationStatistics', '类别'],
  ['LevelStatistics', '级别'],
  ['SystemStatistics', '所属应用系统'],
  ['DeptStatistics', '归属机构']
])
const getDataObject = async () => {
  const data = await reportManageApi.reportManageDataObject()
  console.log('data', data)
  dataObjectList.value = data
  data.forEach((item) => {
    objectMap.set(item.key, item.value)
  })
}

const getTempDetail = async () => {
  const data = await reportTempApi.reportTempGet({ id: route.query.tempId })
  console.log('data', data)
  menuList.value = convertData(data.context)
  console.log('menuList.value', menuList.value)
}

const getReportDetail = async () => {
  const data = await reportManageApi.reportManageGet({ id: route.query.id })
  // menuList.value = convertData(data.tempVO)
  menuList.value = JSON.parse(data.composing)
}

onMounted(() => {
  // 获取数据类别下拉
  getDataObject()
  if (route.query.id) {
    // 获取报表详情
    getReportDetail()
  } else {
    // 获取模板详情
    getTempDetail()
  }

  setTimeout(() => {
    dragTable()
    dragChart()
  }, 1000)
})
</script>
<style lang="scss">
.item {
  background: red;
}
.chart-wrap {
  width: calc(100% - 400px);
}
.chart-list {
  display: flex;
  flex-wrap: wrap;
}
.Table-css {
  width: 100%;
  margin-bottom: 12px;
  // height: 100px;
  // background-color: red;
}
.Pie-css {
  width: 50%;
  margin-bottom: 12px;
  height: 350px;
  // background-color: blue;
}
.Bar-css {
  width: 50%;
  margin-bottom: 12px;
  height: 350px;
  // background-color: green;
}
.Line-css {
  width: 50%;
  margin-bottom: 12px;
  height: 350px;
  // background-color: green;
}
</style>
